/*
 * BanBu_ChatSmileCell
 * @description 本文件提供聊天界面对话界面的super cell
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供聊天界面对话界面的super cell
 */

#import "BanBu_ChatSmileCell.h"
#import "AppDataManager.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_BubbleViewController.h"
#import "BanBuAPIs.h"

@implementation BanBu_ChatSmileCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        
        _atLeft = NO;
        _showFrom=NO;
        _status = ChatStatusNone;
        _type = ChatCellTypeText;        
        
        _bkView = [[UIImageView alloc] initWithFrame:CGRectZero];
        _bkView.backgroundColor = [UIColor clearColor];
        
        [self.contentView addSubview:_bkView];
        
        //头像
        _avatar = [[UIImageView alloc] initWithFrame:CGRectMake(18, self.bounds.size.height - 35, 30, 30)];
        
        _avatar.image = [UIImage imageNamed:@"default.png"];
        _avatar.layer.cornerRadius = 20.0f;
        _avatar.layer.masksToBounds = YES;
        
        [self.contentView addSubview:_avatar];
        
        UITapGestureRecognizer *avatarTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushProfile)];
        _avatar.userInteractionEnabled = YES;
        avatarTap.numberOfTapsRequired = 1;
        [_avatar addGestureRecognizer:avatarTap];
        [avatarTap release];
        
        //发送状态
        _statusView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self insertSubview:_statusView atIndex:0];
        
        _statusLabel=[[UILabel alloc]initWithFrame:CGRectZero];
        [_statusView insertSubview:_statusLabel atIndex:0];
        _statusLabel.textColor=[UIColor whiteColor];
        [_statusLabel setTextAlignment:kTextAlignmentCenter];
        _statusLabel.font=[UIFont systemFontOfSize:11];
        _statusLabel.numberOfLines=0;
        _statusLabel.backgroundColor=[UIColor clearColor];

        
        //时间、距离的背景
        _bgView = [[UIView alloc]initWithFrame:CGRectMake(75, 7.0, 170, 18)];
        _bgView.backgroundColor = [UIColor grayColor];
        _bgView.alpha = 0.2;
        _bgView.layer.cornerRadius = 8;
        [self addSubview:_bgView];
        
        //时间
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(75, 7.0, 100, 18)];
        _timeLabel.backgroundColor=[UIColor clearColor];
        _timeLabel.layer.cornerRadius = 4.0;
        _timeLabel.textAlignment = kTextAlignmentCenter;
        _timeLabel.textColor = [UIColor whiteColor];
        _timeLabel.font = [UIFont systemFontOfSize:14];
        _timeLabel.hidden = YES;
        [self addSubview:_timeLabel];
        
        // 距离
        _demeterLabel=[[UILabel alloc]initWithFrame:CGRectMake(175, 7, 100, 18)];
        _demeterLabel.backgroundColor=[UIColor clearColor];
        _demeterLabel.layer.cornerRadius=4.0;
        _demeterLabel.textAlignment=kTextAlignmentLeft;
        _demeterLabel.textColor=[UIColor whiteColor];
        _demeterLabel.font=[UIFont systemFontOfSize:14];
        _demeterLabel.hidden=YES;
        [self addSubview:_demeterLabel];
        
        
        // 来自
        _fromLabel=[[UILabel alloc]initWithFrame:CGRectZero];
        _fromLabel.backgroundColor=[UIColor grayColor];
        _fromLabel.alpha=.5;
        _fromLabel.textColor = [UIColor whiteColor];
        _fromLabel.layer.cornerRadius=4.0;
        _fromLabel.textAlignment=kTextAlignmentLeft;
        _fromLabel.font=[UIFont systemFontOfSize:12];
        _fromLabel.userInteractionEnabled=YES;
        _fromLabel.hidden=YES;
        [self addSubview:_fromLabel];
        
        // 点击的手势 进入破冰语、涂鸦、魔法工具箱、悄悄话等界面
        UITapGestureRecognizer *tapGester=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(iceBreak)];
        tapGester.numberOfTapsRequired=1;
        [_fromLabel addGestureRecognizer:tapGester];
        [tapGester release];
        
        // 长按手势 改变 颜色
        UILongPressGestureRecognizer *longRecognizer=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(changePic:)];
        
        longRecognizer.minimumPressDuration = 0.8f;
        
        [self addGestureRecognizer:longRecognizer];
        [longRecognizer release];
        
        //单击
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changePicTap:)];
        [self addGestureRecognizer:tap];
        [tap release];
    }
    return self;
}

-(void)dealloc
{
    [_bkView release],_bkView = nil;
   
    
//    [_verifyView release],_verifyView = nil;
    [_avatar release], _avatar = nil;
    [_statusView release],_statusView = nil;
    
    [_bgView release],_bgView = nil;
    [_content release],_content = nil;
    [_chatid release], _chatid = nil;
    [_userid release],_userid = nil;
    [_statusLabel release],_statusLabel = nil;
    [_fromLabel release], _fromLabel = nil;
    [_from release],_from = nil;
    [_timeLabel release],_timeLabel = nil;
    [_demeterLabel release],_demeterLabel = nil;
    _delegate = nil;
    [super dealloc];
}

#pragma mark - 整行的点击、长按事件
//单击事件
-(void)changePicTap:(UITapGestureRecognizer *)tap
{
    if (_type == CHatCellTYpeHints)//信息类型为提示信息  屏蔽掉单击事件
    {
        //跳转到申请页面，根据chatid来判断到底要不要跳转，如果是银行提示就不跳转，如果是会员提示就跳转，会员提示是自己生成的，所以id是有后缀的如：******-******-******.1000
        if (![[self.chatid pathExtension] isEqualToString:@""])//说明有后缀
        {
            //跳到指定页
        }
        return;
    }
    
    if (self.cellChatStatus == 0 || self.cellChatStatus == 2)
    {
        if([_delegate respondsToSelector:@selector(menuShow:tableCell:)]&&_delegate)
        {
            [_delegate menuShow:_bkView tableCell:self];
        }
    }
}
/*
 
 
 
 */

//长按事件
-(void)changePic:(UILongPressGestureRecognizer *)sender
{
    // 先判断 创建 menu
    if (_type == CHatCellTYpeHints)//信息类型为提示信息  屏蔽掉单击事件
    {
        //跳转到申请页面，根据chatid来判断到底要不要跳转，如果是银行提示就不跳转，如果是会员提示就跳转，会员提示是自己生成的，所以id是有后缀的如：******-******-******.1000
        if (![[self.chatid pathExtension] isEqualToString:@""])//说明有后缀
        {
            //跳到指定页
        }
        return;
    }
    
    if ([self.from isEqualToString:@"snap"])//阅后即焚
    {
        switch (sender.state)
        {
            case UIGestureRecognizerStateBegan:
            {
                if([_delegate respondsToSelector:@selector(showSnapImageTabeCell:)]&&_delegate)
                {
                    [_delegate showSnapImageTabeCell:self];
                }
            }
                break;
            case UIGestureRecognizerStateEnded:
            {
                //停止播放
                if ([_delegate respondsToSelector:@selector(dismissSnapImageTabeCell:)])
                {
                    [_delegate dismissSnapImageTabeCell:self];
                }
            }
            default:
                break;
        }
    }
    else if(sender.state==UIGestureRecognizerStateBegan)
    {
        if([_delegate respondsToSelector:@selector(menuShow:tableCell:)]&&_delegate)
        {
            [_delegate menuShow:_bkView tableCell:self];
        }
    }
}

#pragma mark - 头像的点击事件
-(void)pushProfile
{
    if (_atLeft)
    {
        if ([_delegate respondsToSelector:@selector(pushnext)])
        {
            [_delegate pushnext];
        }
    }
    else
    {
        if ([_delegate respondsToSelector:@selector(pushself)])
        {
            [_delegate pushself];
        }
    }
}

#pragma mark - fromLable点击事件
//跳转到来自的地方
-(void)iceBreak
{
    if(!(_delegate&&[_delegate respondsToSelector:@selector(pushTheNextViewController:)]))
    {
        return;
    }
    [_delegate pushTheNextViewController:_from];
}

#pragma mark - 响应方法
- (void)setAvatarImage:(NSString *)imageStr
{
//    _avatar.layer.cornerRadius = 5.0f;
//    _avatar.layer.masksToBounds = YES;
    [_avatar setImageWithURL:[NSURL URLWithString:imageStr] placeholderImage:[UIImage imageNamed:@"default.png"] andType:1];
}

////设置加v
//- (void)setVerify:(BOOL)_flag
//{
////    _verifyView.hidden = _flag;
//}

- (void)setAtLeft:(BOOL)atLeft
{
    _atLeft = atLeft;
    NSString * fileName ;
    
    //判断气泡是否存在
    if ([MyAppDataManager.bubbleNameDic valueForKey:[NSString stringWithFormat:@"%d",self.bubbleID]])
    {
        fileName =  [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"]stringByAppendingPathComponent:[MyAppDataManager.bubbleNameDic valueForKey:[NSString stringWithFormat:@"%d",self.bubbleID]]];
    }
    else if (self.bubbleID >= MyAppDataManager.bubbleNameDic.count)//当bubbleid大于现在的所有的时候就不下载
    {
        fileName = [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"]stringByAppendingPathComponent:@"bubble_0"];
    }
    else
    {
        BanBu_BubbleViewController * bubble= [[[BanBu_BubbleViewController alloc]init] autorelease];
        [bubble getDefault];
        
        fileName = [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"]stringByAppendingPathComponent:@"bubble_0"];
        
        //调用BanBu_BubbleViewController下载图片
        [ThemeManager getMore:BanBu_GetMoreBubbleImage];
    }
    
    if(_atLeft)
    {
        fileName = [fileName stringByAppendingPathComponent:@"aio_friend_bg_nor@2x.png"];
        _bkView.image = [UIImage imageWithContentsOfFile:fileName];
    }
    else
    {
        fileName = [fileName stringByAppendingPathComponent:@"aio_user_bg_nor@2x.png"];
        _bkView.image = [UIImage imageWithContentsOfFile:fileName];
    }
}

//设置消息时间和距离
-(void)setMsgTime:(BOOL)showTime withTime:(NSString *)time withDmeter:(NSString *)dmeter
{
    _showTime = showTime;
    
    if (_showTime)
    {
        _timeLabel.hidden = NO;
        _demeterLabel.hidden= NO;
        _bgView.hidden = NO;
        
        _timeLabel.text = [time substringWithRange:NSMakeRange(5, [time length]-5-3)];
        _demeterLabel.text = [MyAppDataManager IsInternationalLanguage:dmeter];
        CGSize size = [_demeterLabel.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(260-20, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
        self.bgView.frame = CGRectMake(75, 7.0, 100+size.width+10, 18);
    }
    else
    {
        _timeLabel.hidden = YES;
        _demeterLabel.hidden= YES;
        _bgView.hidden = YES;
        
        _timeLabel.text = nil;
        _demeterLabel.text=nil;
    }
}

// 重写cell 的setediting
- (void)setStatus:(ChatStatus)status
{
    if (self.atLeft)
    {
        _statusView.image = nil;
        _statusLabel.text=@"";
        return;
    }
    
    _statuss = status;
    
    _statusView.image = nil;
    
    NSArray *statusImages = statusImagesArr;
    
    NSArray *statusWords= statusWordsArr;
    
    if (statusImages.count <= status)
    {
        _statusView.image = nil;
    }
    else
    {
        _statusView.image = [[UIImage imageNamed:[statusImages objectAtIndex:status]]stretchableImageWithLeftCapWidth:5 topCapHeight:5];
        CGFloat f=[[statusWords objectAtIndex:status] sizeWithFont:[UIFont systemFontOfSize:11]].width;
        _statusView.frame=CGRectMake(StatusViewRect.origin.x-(f-23), StatusViewRect.origin.y, f, StatusViewRect.size.height);
        _statusLabel.frame=CGRectMake(0, 0,_statusView.frame.size.width, _statusView.frame.size.height);
        _statusLabel.text=[statusWords objectAtIndex:status];
    }
}

#pragma mark - fromLabel
//msgfrom：bw（不文明用语）、pb（破冰语）、ty（涂鸦）、mo（默认）、hints（提示）、specialApp（开放平台）、mg（魔法工具箱）、snap（阅后即焚）
-(void)setShowFrom:(BOOL)showFrom
{
    _showFrom = showFrom;
    
    _fromLabel.hidden = !_showFrom;
    if(!_showFrom)
    {
        _fromLabel.text=nil;
    }
    
    if (_showFrom)
    {
        if ([_from isEqualToString:@"bw"])//不文明用语，在服务器端替换成**，客户端不再判断这一属性
        {//不文明用语
            if (_atLeft)
            {
                _fromLabel.hidden = YES;
                return;
            }
            _fromLabel.text = NSLocalizedString(@"politeSay", nil);
        }
        else if([_from isEqual:@"pb"])
        {//破冰语
            _fromLabel.text= NSLocalizedString(@"searchIce", nil);
        }
        else if([_from isEqual:@"ty"])
        {//涂鸦
            _fromLabel.text = NSLocalizedString(@"comefromtuya", nil);
        }
        else if([_from isEqual:@"mg"])
        {//魔法工具箱
            _fromLabel.text = NSLocalizedString(@"magicTool", nil);
        }
        else if ([_from isEqualToString:@"snap"])
        {//阅后即焚
            _fromLabel.text = NSLocalizedString(@"burnAfterReading", nil);
        }
        else if([_from isEqual:@"sp"])
        {
            _fromLabel.text = nil;
            _fromLabel.hidden = YES;
        }
        else if ([_from isEqualToString:@"store"])//表情商店
        {
            _fromLabel.text = NSLocalizedString(@"emoStore", nil);
        }
        else if ([_from isEqualToString:@"collect"] || [_from isEqualToString:@"collectimage"])
        {
            _showFrom = NO;
            return;
        }
        else//其他类型的都不显示（未定义的类型）
        {
            _fromLabel.text = NSLocalizedString(@"comefromUndefine", nil);
        }
        
        
        CGFloat len = [_fromLabel.text sizeWithFont:[UIFont systemFontOfSize:12]].width;
        _fromLabel.frame=CGRectMake(35, 0, len, 18);
    }
    else
    {
        _fromLabel.text=nil;
    }
    
    if(_showTime)
    {
        CGRect rect=_fromLabel.frame;
        rect.origin.y=rect.origin.y+TimeLabelHeight;
        _fromLabel.frame=rect;
    }
}

//设置ShowLable的Frame
-(void)setShowFromFrame:(ChatMsgType)type
{
    CGFloat fromlabellen = [_fromLabel.text sizeWithFont:[UIFont systemFontOfSize:12]].width+10;
    CGRect fromLabelRect =CGRectMake(60, 0, fromlabellen, 18);
    _fromLabel.textAlignment=kTextAlignmentCenter;
    fromLabelRect.origin.y = _bkView.frame.origin.y + _bkView.frame.size.height;
    
    if (!_atLeft)
    {
        fromLabelRect.origin.x = 265-fromlabellen;
    }
    
    _fromLabel.frame = fromLabelRect;
}

//设置气泡的frame
-(void)setBubbleFrame
{
    if (!_atLeft)
    {
        switch (self.bubbleID)//右侧的气泡
        {
            case 0:
//                _bkView.image = [_bkView.image stretchableImageWithLeftCapWidth:20.0 topCapHeight:30.0];
                _bkView.image = [_bkView.image stretchableImageWithLeftCapWidth:30.0 topCapHeight:25.0];
                break;
            default:
                _bkView.image = [_bkView.image stretchableImageWithLeftCapWidth:30.0 topCapHeight:25.0];
                break;
        }
    }
    else
    {
        switch (self.bubbleID)//左侧的气泡，以后要用对方传回来的气泡id，根据id选择扩展的选项
        {
            case 0:
//                _bkView.image = [_bkView.image stretchableImageWithLeftCapWidth:20.0 topCapHeight:30.0];
                _bkView.image = [_bkView.image stretchableImageWithLeftCapWidth:31.0 topCapHeight:25.0];
                break;
            default:
                _bkView.image = [_bkView.image stretchableImageWithLeftCapWidth:31.0 topCapHeight:25.0];
                break;
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    float height = self.contentView.frame.size.height;
        
    _bkView.frame = BKViewRect(_bkViewWidth, height-2*CellMarge);
    //设置气泡frame
    [self setBubbleFrame];
    
    if (_atLeft)
    {
        _statusView.frame = CGRectZero;
    }
    else
    {
        CGFloat f=[_statusLabel.text sizeWithFont:[UIFont systemFontOfSize:11]].width;
        
        CGRect frame = StatusViewRect;
        frame.origin.x = frame.origin.x - f + 27;
        frame.size.width = f+3;

        _statusView.frame = frame;
    }

    if (_showTime)
    {
        CGSize size = [_demeterLabel.text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(260-20, 1000) lineBreakMode:kTextLineBreakByWordWrapping];
        self.bgView.frame = CGRectMake(75, 7.0, 100+size.width+10, 18);
    }
    else
    {
        self.bgView.frame = CGRectZero;
    }
}

//设置cell的各种信息
-(void)setChatCellInfo:(NSDictionary *)amsg
{
    //先找出来气泡的id，如果没有就去下载
    self.height = [VALUE(KeyHeight, amsg) integerValue];
    self.bubbleID = [[amsg valueForKey:KeyBubbleID] integerValue];
    self.chatid = [amsg valueForKey:KeyChatid];
    self.content = VALUE(KeyContent, amsg);
    self.cellChatStatus = [VALUE(KeyStatus, amsg) integerValue];//用于判断是单击还是长按
    self.userid = MyAppDataManager.chatuid;
    self.mediastatus = [[amsg valueForKey:KeyMediaStatus] integerValue];
    BOOL me = [VALUE(KeyMe,amsg) boolValue];
    self.atLeft = !me;
    
    if(self.atLeft == NO)
    {
        [self setAvatarImage:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"uface"]];
//        [self setVIPFlag:[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"userlevel"] integerValue]>0];
        
//        BOOL bl = [[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"verify"] boolValue];
//        [self setVerify:!bl];
    }
    else
    {
        [self setAvatarImage:[amsg valueForKey:KeyUface]];
//        [self setVIPFlag:[[amsg valueForKey:@"userlevel"] integerValue]>0];
//        [self setVerify:![[amsg valueForKey:@"verify"] isEqual:@"y"]];
    }
    
    self.type = [VALUE(KeyType, amsg) integerValue];
    self.status = [VALUE(KeyStatus, amsg) integerValue];
    
    self.from=VALUE(KeyShowFrom, amsg);
    
    if (![VALUE(KeyShowFrom, amsg) isEqual:@"mo"])
    {
        if (self.atLeft && [self.from isEqualToString:@"bw"])
        {
            self.showFrom = NO;
        }
        else if([self.from isEqualToString:@"collect"])
        {
            self.showFrom = NO;
        }
        else
        {
            self.showFrom = YES;
        }
    }
    else
    {
        self.showFrom = NO;
    }
    
    BOOL showTime = YES;
    
    //默认第一行显示时间
    showTime = [VALUE(KeyShowtime, amsg) boolValue];
    [self setMsgTime:showTime withTime:[amsg valueForKey:KeyStime] withDmeter:[amsg valueForKey:KeyDmeter]];
}

@end
